<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="密码" prop="pass">
      <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import  {routerStore} from  "../stores/counter";
import type { FormInstance, FormRules } from 'element-plus'
import  {userLogin} from  "../service/userService"
import  Main from   '@/views/MainView.vue';
import Student from   "@/views/StudentView.vue";
import Leave from   "@/views/LeaveView.vue";
import addLeave from  "@/views/AddLeave.vue"
import dataanalysis from  "@/views/DataAnalysis.vue"

let $router  = useRouter();
let $Store = routerStore();

let routerInfo:any = {
  "student":Student,
  "leave":Leave,
  "addleave":addLeave,
   dataanalysis
}

const ruleFormRef = ref<FormInstance>() //表单元素

const ruleForm = reactive({
  //表单内容
  pass: '',
  username: ''
})
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('用户名不能为空'))
  } else if (value.length < 4 || value.length > 12) {
    callback(new Error('用户名长度只能4到12位'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof ruleForm>>({
  pass: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { pattern: /^[0-9a-z]{6,10}$/i, message: '密码只能是数字字母组成长度6到10位', trigger: 'blur' }
  ],
  username: [{ validator: validateUsername, trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      console.log('submit!')
      console.log(ruleForm)
      let  res  = await userLogin({
        username:ruleForm.username,
        userpwd:ruleForm.pass
      })
      // console.log(res);
      if(res.data.code==200){
        window.localStorage.setItem("token",res.data.token);
        console.log(res.data);
        let  routerList  = res.data.routerList;
        if(routerList.length){
          //防止用户切换 之前的路由数据还有
          $router.removeRoute('main');
          $router.addRoute({
            path:"/main",
            name:"main",
            component:Main
          })

          let defaultRouter  = routerList[0];
          $router.addRoute("main",{path:"",component:routerInfo[defaultRouter.com]});

          routerList.forEach((element:any) => {
            $router.addRoute("main",{name:element.path,path:element.path,component:routerInfo[element.com]})     
          });
        }

        // $router.addRoute("main",{path:"",component:Student});
        // $router.addRoute("main",{path:"student",component:Student});
        // $router.addRoute("main",{path:"leave",component:Leave});
        $Store.initMenuList(routerList);
        window.localStorage.setItem("routerList",JSON.stringify(routerList));
        //console.log($Store);
         $router.push("/main");
        //console.log($router.getRoutes());


      }else{
        alert(res.data.msg);
      } 
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
